/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package person.academy;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "person_academy")
@RequestScoped
public class Main extends Beans {
    //Variables de importación General

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    //Vaiables de importación de otros modulos
    //Variables del modulo
    private Find person_academyFind = new Find();
    private List<Beans> person_academyList = new ArrayList<>();
    //Variables locales
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    private void load() {
        try {
            map.clear();
            map.put("a.id = " + logged.getDetailId(), " ");

            person_academyList.clear();
            person_academyList = person_academyFind.byMap(map);

            setId(person_academyList.get(0).getId());
            setId_persona(person_academyList.get(0).getId_persona());
            setId_pais(person_academyList.get(0).getId_pais());
            setIdl_nivel(person_academyList.get(0).getIdl_nivel());
            setInicio(person_academyList.get(0).getInicio());
            setFin(person_academyList.get(0).getFin());
            setTitulo(person_academyList.get(0).getTitulo());
            setEspecialidad(person_academyList.get(0).getEspecialidad());
            setInstitucion(person_academyList.get(0).getInstitucion());
            getCountryBeans().setNombre(person_academyList.get(0).getCountryBeans().getNombre());

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {
            //Verifica si se ha seleccionado un registro
            if (logged.getMasterId() == 0) {
                throw new Exc("m25");
            }

            //se carga el mapa con los valores
            map.clear();
            map.put("id_persona = " + logged.getMasterId(), " AND ");
            map.put("id_pais = " + getId_pais(), " AND ");
            map.put("idl_nivel = " + getIdl_nivel(), " AND ");
            map.put("inicio = '" + getInicio() + "'", " AND ");
            map.put("fin = '" + getFin() + "'", " AND ");
            map.put("lower(titulo) = '" + getTitulo().toLowerCase() + "'", " AND ");
            map.put("lower(especialidad) = '" + getEspecialidad().toLowerCase() + "'", " AND ");
            map.put("lower(institucion) = '" + getInstitucion().toLowerCase() + "'", " ");

            //Verifica si el registro existe, de lo contrario lo inserta
            if (person_academyFind.byExist(map)) {
                throw new Exc("m5");
            }
            if (getInicio().compareTo(getFin()) >= 0) {
                throw new Exc("m26");
            }
            sql = "INSERT INTO public.persona_academia (id_persona, id_pais, idl_nivel, inicio, fin, titulo, especialidad, institucion) "
                    + "VALUES (" + logged.getMasterId() + ", " + getId_pais() + ", "
                    + getIdl_nivel() + ", "
                    + "'" + getInicio() + "', "
                    + "'" + getFin() + "', "
                    + "'" + getTitulo() + "', "
                    + "'" + getEspecialidad() + "', "
                    + "'" + getInstitucion() + "')";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);

            //Localiza el id del registro recien insertado, con la llave única
            person_academyList = person_academyFind.byMap(map);

            //Asigna el id del registro insertado a la variable global
            logged.setDetailId(person_academyList.get(0).getId());

            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void update() {
        try {
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m6");
            }
            map.clear();
            map.put("a.id <> " + logged.getDetailId(), " AND ");
            map.put("id_persona = " + logged.getMasterId(), " AND ");
            map.put("id_pais = " + getId_pais(), " AND ");
            map.put("idl_nivel = " + getIdl_nivel(), " AND ");
            map.put("inicio = '" + getInicio() + "'", " AND ");
            map.put("fin = '" + getFin() + "'", " AND ");
            map.put("lower(titulo) = '" + getTitulo().toLowerCase() + "'", " AND ");
            map.put("lower(especialidad) = '" + getEspecialidad().toLowerCase() + "'", " AND ");
            map.put("lower(institucion) = '" + getInstitucion().toLowerCase() + "'", " ");

            //Verifica si el registro existe, de lo contrario lo inserta
            if (person_academyFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "UPDATE public.persona_academia SET "
                    + "id_persona = " + logged.getMasterId() + ", "
                    + "id_pais = " + getId_pais() + ", "
                    + "idl_nivel = " + getIdl_nivel() + ", "
                    + "inicio = '" + getInicio() + "', "
                    + "fin = '" + getFin() + "', "
                    + "titulo = '" + getTitulo() + "', "
                    + "especialidad = '" + getEspecialidad() + "', "
                    + "institucion = '" + getInstitucion() + "' "
                    + "WHERE id = " + logged.getDetailId();

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);

            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }

    }

    public void delete() {
        try {
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id
            deleteById(logged.getDetailId());
            clear();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        sql = "DELETE FROM public.persona_academia "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
    }

    public void clear() {
        clearBeans();
        logged.setDetailId(0);
    }

    public void selectedTempId(int tempId) {
        logged.setDetailId(tempId);
        load();
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
